package icu.bughub.app.app.ui.screens

import androidx.compose.animation.core.FastOutSlowInEasing
import androidx.compose.animation.core.animateDpAsState
import androidx.compose.animation.core.tween
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Notifications
import androidx.compose.material.icons.filled.Search
import androidx.compose.material3.Icon
import androidx.compose.material3.LeadingIconTab
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Tab
import androidx.compose.material3.TabPosition
import androidx.compose.material3.TabRow
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.viewmodel.compose.viewModel
import icu.bughub.app.app.ui.components.ArticleItem
import icu.bughub.app.app.ui.components.NotificationContent
import icu.bughub.app.app.ui.components.SwiperContent
import icu.bughub.app.app.ui.components.TopAppBar
import icu.bughub.app.app.ui.components.VideoItem
import icu.bughub.app.app.viewmodel.ArticleViewModel
import icu.bughub.app.app.viewmodel.MainViewModel
import icu.bughub.app.app.viewmodel.VideoViewModel

/**
 * @author huangzehui
 * @date 2024/5/14 13:22 周二
 * @description
 *
 * 页面初建
 * https://www.bilibili.com/video/BV1aS4y1D7dv?p=3&vd_source=e07cc8cc94eb22bd76722071b03cd199
 *
 */

@OptIn(ExperimentalFoundationApi::class)
@Composable
fun StudyScreen(vm: MainViewModel = viewModel(),
                articleViewModel: ArticleViewModel = viewModel(),
                videoViewModel: VideoViewModel = viewModel()
) {
    Column(modifier = Modifier) {
        // 标题栏
        TopAppBar(
            modifier = Modifier.padding(horizontal = 8.dp) // 这里设置了，就不需要下面的 Spacer
        ) {
//            Spacer(modifier = Modifier.width(8.dp))
            // 搜索按钮
            Surface(
                modifier = Modifier
                    .clip(RoundedCornerShape(16.dp))
                    .weight(1f),
                color = Color(0x4DFFFFFF)
            ) {
                Row(
                    modifier = Modifier.padding(horizontal = 8.dp, vertical = 4.dp),
                    verticalAlignment = Alignment.CenterVertically,
                ) {
                    Icon(
                        imageVector = Icons.Filled.Search,
                        contentDescription = null,
                        tint = Color.White,
                        modifier = Modifier.size(14.dp)
                    )

                    Text(
                        text = "搜索感兴趣的咨询内容", color = Color.White, fontSize = 12.sp,
                        maxLines = 1,
                        overflow = TextOverflow.Ellipsis
                    )
                }
            }

            Spacer(modifier = Modifier.width(8.dp))

            // 学习进度
            Column(
                horizontalAlignment = Alignment.CenterHorizontally,
                verticalArrangement = Arrangement.Center
            ) {
                Text(text = "学习", fontSize = 10.sp, color = Color.White)
                Text(text = "进度", fontSize = 10.sp, color = Color.White)
            }

            Spacer(modifier = Modifier.width(8.dp))
            // 百分比
            Text(text = "26%", fontSize = 12.sp, color = Color.White)

            Spacer(modifier = Modifier.width(8.dp))

            Icon(
                imageVector = Icons.Filled.Notifications,
                contentDescription = null,
                tint = Color.White
            )
        }

        // 分类标签

        // 文本的宽度
        val textWidthList by remember {
            mutableStateOf(mutableListOf(0f))
        }

        TabRow(selectedTabIndex = vm.categoryIndex,
            containerColor = Color(0x0F149EE7),
            indicator = { tabPositions: List<TabPosition> ->
                // 当前方法是定义指示器的
                val selectedTabIndex = vm.categoryIndex
                val targetPosition = tabPositions[selectedTabIndex]

//                Log.e("young_test90909090", "targetPosition = ${targetPosition} = ${k[selectedTabIndex]}")

                if (selectedTabIndex < tabPositions.size) {
//                    val indicatorWidth = targetPosition.width * 0.3f
                    // 将值转为 dp，调用 toDp()，必须使用 with(LocalDensity.current)，否则无法调用到 toDp() 方法
                    val indicatorWidth = with(LocalDensity.current) {
                        textWidthList[selectedTabIndex].toDp()
                    }

                    val targetValue =
                        (targetPosition.right - targetPosition.left) / 2f - indicatorWidth / 2f

                    val currentTabWidth by animateDpAsState(
//                        targetValue = targetPosition.width,
                        targetValue = indicatorWidth,
                        animationSpec = tween(durationMillis = 250, easing = FastOutSlowInEasing)
                    )
                    val indicatorOffset by animateDpAsState(
//                        targetValue = targetPosition.left,
                        targetValue = targetPosition.left + targetValue,
                        animationSpec = tween(durationMillis = 250, easing = FastOutSlowInEasing)
                    )

                    Box(
                        modifier = Modifier
                            .wrapContentSize(Alignment.BottomStart)
                            .offset(x = indicatorOffset)
                            .width(currentTabWidth)
                            .height(3.dp)
                            .clip(shape = RoundedCornerShape(16.dp))
                            .background(color = MaterialTheme.colorScheme.primary)
                    )
//                    TabRowDefaults.Indicator(
//                        Modifier.tabIndicatorOffset(tabPositions[selectedTabIndex])
//                    )
                }
            }) {
            vm.categories.forEachIndexed { index, category ->
                Tab(selected = index == vm.categoryIndex,
                    selectedContentColor = Color(0xFF149EE7),
                    unselectedContentColor = Color(0xFF666666),
                    onClick = {
                        vm.updateCategoryIndex(index)
                    }) {
                    Text(
                        text = category.title,
                        modifier = Modifier.padding(vertical = 8.dp),
                        onTextLayout = {
                            // 这里获取文案的宽度
                            textWidthList.add(index, it.multiParagraph.width)
                        })
                }
            }
        }

        // 类型
        TabRow(
            selectedTabIndex = vm.typeIndex,
            containerColor = Color.Transparent,
            indicator = {},
            divider = {}
        ) {
            vm.types.forEachIndexed { index, dataType ->
                LeadingIconTab(
                    selected = index == vm.typeIndex,
                    selectedContentColor = Color(0xFF149EE7),
                    unselectedContentColor = Color(0xFF666666),
                    onClick = {
                        vm.updateTypeIndex(index)
                    },
                    text = {
                        Text(
                            text = dataType.title,
                            modifier = Modifier.padding(vertical = 8.dp),
                            fontSize = 16.sp
                        )
                    },
                    icon = {
                        Icon(imageVector = dataType.icon, contentDescription = null)
                    })
            }
        }

        LazyColumn {
            item {
                // 轮播图
                SwiperContent(vm = vm)
            }

            item {
                // 通知公告
                NotificationContent(vm = vm)
            }

            if (vm.showArticleList){
                // 新闻列表
                items(count = articleViewModel.list.size) { articleIndex ->
                    ArticleItem(articleViewModel.list[articleIndex])
                }
            } else {
                // 视频列表
                items(count = videoViewModel.list.size) {index: Int ->
                    VideoItem(videoViewModel.list[index])
                }

            }

        }
    }
}


